from apps.neo4j.InterfaceSet import Neo4jHandler as neo4jHandler
from apps.neo4j.gensim_train.train_result_api import gensim_handler

def GetProblemData_By_ProduceCode(value):
    '''

    :param value:传入的产品型号
    :return: 该产品现有的故障处理策略（list_json）
    '''
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    value1 = value.replace(".", "/")
    '''
    
    
    data = handler.matchReasonByPhenomenon(value1)

    listofJson = []

    for i in range(len(data)):
        node = data[i][list(data[0].keys())[0]]
        node_dict = handler.pyneo2j_ProblemNode_to_List(node)
        # print(type(node_dict))
        listofJson.append(node_dict)
    '''

    return handler.matchReasonByPhenomenon(value1)


def tree1_data(value):
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    data = handler.getLogicalTreeData_ZongCheng(value)
    # print(len(data))
    datas = handle_tree_data(data)
    return datas


def handle_tree_data(datas):
    tree_data = {
        'name': "设备",
        'children': [

        ]
    }
    parts = []
    for data in datas:
        if data['part'] in parts:
            pass
        else:
            parts.append(data['part'])

    # print(parts)
    for part in parts:
        tree_data['children'].append({'name': part, 'children': []})

    # print(tree_data)

    index = 0
    for part in parts:
        children = []
        for data in datas:
            if data['part'] == part:
                if data['child_part'] in children:
                    pass
                else:
                    children.append(data['child_part'])

        for child in children:
            tree_data['children'][index]['children'].append({'name': child, 'children': []})
        index += 1

    # print(tree_data)

    index = 0
    for part in parts:
        children = []
        for data in datas:
            if data['part'] == part:
                if data['child_part'] in children:
                    pass
                else:
                    children.append(data['child_part'])

        fault_child = []
        for child in children:
            fault_child.append([])

        for data in datas:
            if data['part'] == part:
                child_index = 0
                for child in children:
                    if data['child_part'] == child:
                        fault_child[child_index].append(data['fault'])
                    child_index += 1
        # print(fault_child)

        child_index = 0
        for fault1 in fault_child:
            for fault2 in fault1:
                # tree_data['children'][index]['children'][child_index]['children'].append({'name': fault2, 'value': 111})
                tree_data['children'][index]['children'][child_index]['children'].append({'name': fault2})
            child_index += 1

        index += 1

    return tree_data


def fuzzy_query(value):
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    datas = handler.matchReasonByPhenomenon_gensim(value)
    # print(data)
    # for dd in data:
    #     print(dd)
    # print(len(data))
    # print(data[0])
    # print(data[0][0])
    # print(data[0][1])
    result_data = []
    for data in datas:
        for data1 in data[1]:
            aa = round(data[0] * 100, 2)

            data1['similarity'] = str(aa) + '%'
            result_data.append(data1)

    return result_data


# print(fuzzy_query("声音大大"))


def add_node_relation(value):
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    label = handler.Node_Relation_Add(value)
    if label == 0:
        return 0
    else:
        return 1


def all_data():
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    data = handler.matchReasonByPhenomenon()
    # print(data)
    return data

def all_Relation_Json():
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    data = handler.matchAllRelationJson()
    return data

def exactSearch(pid):
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    data = handler.exactSearch(pid)
    return data

def details(pid, nid):
    handler = neo4jHandler.Neo4j_Handle()
    handler.connectDB()
    data = handler.details(pid, nid)
    return data

def fuzzy_unique_query(query):
    data = fuzzy_query(query)
    # print(data)
    res = []
    sorce = {}
    for dd in data:
        sim = float(dd['similarity'].split("%")[0])
        if dd['Phenomenon'] in sorce.keys():
            if sorce[dd['Phenomenon']] < sim:
                sorce[dd['Phenomenon']] = sim
        else:
            sorce[(dd['id'], dd['Phenomenon'])] = sim

    tuplelist_sorted = sorted(sorce.items(),key=lambda x: x[1], reverse=True)
    print(tuplelist_sorted)

    index = 1
    for k,v in tuplelist_sorted:
    # for k,v in sorce.items():
        temp = {}
        temp['index'] = index
        index += 1
        temp['Phenomenon'] = k[1]
        temp['similarity'] = str(v) + '%'
        temp['id'] = k[0]
        res.append(temp)
    print(res)
    return res
